<template>
	<view class="container">


		<!-- 计划信息卡片 -->
		<view class="card plan-info">
			<view class="card-header">
				<text class="card-title">计划信息</text>
			</view>

			<view class="info-item" style="		border-bottom: 1rpx solid #eeeeee;		padding-bottom: 20rpx;">
				<text class="label">跟进方式</text>
				<text class="value">{{genjinStatus}}</text>
			</view>

			<view class="info-item">
				<text class="label">提醒时间</text>
				<text class="value">{{detailData.remindTime}}</text>
			</view>

			<view class="info-item">
				<text class="label">跟进内容</text>
				<!-- <text class="value content-text">{{detailData.neirong}}</text> -->
				<u--textarea v-model="detailData.neirong" placeholder="文本域已被禁用" border="none" autoHeight
					disabled></u--textarea>
			</view>

			<view class="info-item">
				<text class="label">附件</text>
				<view class="attachment-list">
					<!-- 	<text class="attachment-item" v-for="(item, index) in detailData.attachmentList" :key="index">
						📎 {{ item.url }}
					</text> -->
					<view class="value contact-info"
						style="margin-bottom: 20rpx; text-align: left; justify-content: space-between;"
						v-for="(item, index) in detailData.attachmentList" :key="index" @click="downFile(item)">
						<u--text :lines="2" :text="item.url.split('/').pop()"> </u--text>
						<!-- <text class="contact-btn" @click="makeCall">拨打</text> -->
						<u-icon name="close" color="#ff0000" size="20" @click="deleteFile(item)"></u-icon>

					</view>
				</view>
			</view>
			<!-- <view class="info-item">
				<u-image :src="ImageUrl"></u-image>
			</view> -->
		</view>

		<!-- 跟进客户卡片 -->
		<view class="card customer-info">
			<view class="card-header">
				<text class="card-title">跟进客户</text>
			</view>

			<view class="customer-header">
				<u-avatar size="40" src="/static/avatar.png"></u-avatar>
				<view class="customer-name">
					<text class="name">{{detailData.userId}}</text>
					<text class="company">-----------</text>
				</view>
			</view>

			<!-- <view class="info-item">
				<text class="label">联系方式:</text>
				<text class="value contact-info">
					<text>138****8888</text>
					<text class="contact-btn" @click="makeCall">拨打</text>
				</text>
			</view> -->

			<view class="info-item">
				<text class="label">最后联系时间:</text>
				<text class="value">{{detailData.uptime}}</text>
			</view>

			<view class="info-item">
				<text class="label">状态:</text>

				<!-- <text class=" status nodue contact-btn" v-if="detailData.expire == 0">未超时</text> -->
				<!-- <text class=" status overdue contact-btn">{{isExpired}}</text> -->

				<u-tag text="未计划" type="warning" plain v-if="isExpired == 2"></u-tag>
				<u-tag text="计划中" type="success" plain v-else-if="isExpired ==1"></u-tag>
				<u-tag text="已完成" plain v-else-if="isExpired ==3"></u-tag>
				<u-tag text="已超时" type="error" plain v-else></u-tag>

			</view>
		</view>

		<!-- 删除按钮确认框 -->
		<u-modal :show="deleteShow" :title="title" :content='content' showConfirmButton showCancelButton buttonReverse
			@confirm="deleteconfirm" @cancel="deletecancel">
			<u--text :lines="2" :text="content"></u--text>
		</u-modal>
		<!-- 底部操作按钮 -->
		<!-- 		<view class="footer">
			<u-button type="primary" @click="markAsCompleted" :customStyle="{
          width: '90%',
          height: '80rpx',
          fontSize: '32rpx'
        }">
				设为完成
			</u-button>
		</view> -->
	</view>
</template>

<script>
	import api from "@/utils/api.js";
	import request from "@/utils/request.js";
	export default {
		data() {
			return {
				fileName: '文件名称',
				ImageUrl: '',
				Id: '',
				fileId: '',
				detailData: [], //详情信息
				deleteShow: false,
				title: '是否删除',
				content: '',
				attachments: [{
						name: '产品介绍.pdf'
					},
					{
						name: '合同草案.docx'
					}
				],
				genjinactions: [{
						name: '📝文字记录',
						id: 1,
					},
					{
						name: '✉️发短信',
						id: 4,
					},
					{
						name: '💬发微信',
						id: 2,
					},
					{
						name: '📞打电话',
						id: 3,
					},
					{
						name: '📧发邮件',
						id: 5,
					},
				],
			}
		},
		computed: {
			genjinStatus() {
				const listData = this.genjinactions;
				const option = listData.find(
					item => item.id == this.detailData.followType
				);
				return option ? option.name : '未知';
			},
			// // 是否超时，计划中
			isExpired() {
				if (this.detailData.status == 2) {
					return "3"
				}
				if (this.detailData.isremind == 1) {
					return new Date(this.detailData.remindTime) < new Date() ? '0' : '1';
				} else if (this.detailData.isremind == 0) {
					return "2"
				}
			},
		},
		onLoad(options) {
			if (options.Id) {
				this.Id = options.Id;
				this.getGenjinDetail(options.Id)
			}
		},
		methods: {
			// 获取详情信息
			getGenjinDetail(id) {
				request(api.genjinDetail + `/${id}`, "GET")
					.then(res => {
						console.log(res);
						if (res.code == 200) {
							this.detailData = res.data;
						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			// 删除附件方法
			delUpLoadList(id) {
				request(api.delUpLoadList + `/${id}`, "DELETE")
					.then(res => {
						console.log(res);
						if (res.code == 200) {
							this.getGenjinDetail(this.Id)
							this.deleteShow = false;
						}
					})
					.catch(err => {
						console.log(err);
					})
			},
			// // 是否超时，计划中
			// isExpired(targetTimeStr) {
			// 	if (this.detailData.status == 1) {
			// 		return new Date(targetTimeStr) < new Date() ? '0' : '1';
			// 	} else {
			// 		return "2"
			// 	}
			// },

			// 使用示例
			// const expired = isExpired("2025-10-20 15:43:36");
			// console.log(expired ? "已过期" : "未过期");
			// 删除附件信息
			deleteFile(item) {
				this.fileId = item.id;
				this.content = item.url.split('/').pop()
				this.deleteShow = true;
			},
			// 确认删除附件方法
			deleteconfirm() {
				this.delUpLoadList(this.fileId);
			},
			// 取消删除
			deletecancel() {
				this.fileId = "";
				this.deleteShow = false;
			},
			// 标记为完成
			markAsCompleted() {
				uni.showModal({
					title: '确认',
					content: '确定要将此计划标记为完成吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showToast({
								title: '已标记为完成',
								icon: 'success'
							})
							// 这里可以添加提交到后端的逻辑
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						}
					}
				})
			},

			// 拨打电话
			makeCall() {
				uni.makePhoneCall({
					phoneNumber: '13800008888'
				})
			},
			// 先获取文件数据，然后创建Blob URL下载
			async blobDownload(url, filename) {
				// const url = `/api/download-proxy?url=${encodeURIComponent(urls)}`;
				try {
					const response = await fetch(url);
					const blob = await response.blob();
					const blobUrl = URL.createObjectURL(blob);

					const link = document.createElement('a');
					link.href = blobUrl;
					link.download = filename || getFilenameFromUrl(url);
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);

					// 清理Blob URL
					setTimeout(() => URL.revokeObjectURL(blobUrl), 100);

					return true;
				} catch (error) {
					console.error('下载失败:', error);
					return false;
				}
			},
			// 下载预览附件文件
			downFile(item) {
				this.fileName = item;
				console.log(item);
				this.ImageUrl = `https://file.jinzhizixun.com.cn/${item.url}`;
				const lastDotIndex = this.ImageUrl.lastIndexOf('.');
				if (lastDotIndex === -1) {
					return '';
				}
				const fileType = this.ImageUrl.substring((lastDotIndex + 1))
				console.log(fileType, "文件类型");
				if (fileType == 'png' || fileType == "jpg" || fileType == "jpeg") {
					uni.previewImage({
						urls: [`https://file.jinzhizixun.com.cn/${item.url}`], // 要预览的图片链接列表
						current: 0, // 当前显示图片的索引
						indicator: 'default', // 指示器类型
						loop: false, // 是否循环预览
						success: (res) => {
							console.log(res);
						}, // 成功回调
						fail: (err) => {
							console.log(err);
						} // 失败回调
					});
				} else {
					// this.downloadFile() //方案一
					// this.simpleDownload(item.url) //方案二
					this.simpleCompatibleDownload(item.url) //方案三
					// this.blobDownload(`https://file.jinzhizixun.com.cn/${item.url}`, item.url)
					// FileDownLoader.blobDownload(`https://file.jinzhizixun.com.cn/${item.url}`, item.url)
					// window.open(`https://file.jinzhizixun.com.cn/${item.url}`); //在当前窗口中打开窗口vue中
					// uni.downloadFile({
					// 	url: `https://file.jinzhizixun.com.cn/${item.url}`,
					// 	success(res) {
					// 		console.log('下载成功', res);
					// 	},

					// 	fail(err) {
					// 		console.log('下载失败', err);
					// 	}
					// });

					// uni.downloadFile({
					// 	url: `https://file.jinzhizixun.com.cn/${item.url}`,
					// 	success: function(res) {
					// 		var filePath = res.tempFilePath;
					// 		console.log(res, "1111");
					// 		plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
					// 			entry.copyTo(plus.io.PUBLIC_DOCUMENTS, '文件名', (newEntry) => {
					// 				resolve(newEntry.fullPath);
					// 			}, reject);
					// 		}, reject);
					// 		// uni.openDocument({
					// 		// 	filePath: filePath,
					// 		// 	showMenu: true,
					// 		// 	success: function(res) {
					// 		// 		console.log('打开文档成功');
					// 		// 	}
					// 		// });
					// 		// uni.saveFile({
					// 		// 	tempFilePath:res.tempFilePath,

					// 		// })
					// 	}
					// });
				}
			},
			// 方案三
			async simpleCompatibleDownload(item) {
				const fileUrl = `https://file.jinzhizixun.com.cn/${item}`;

				// 直接使用浏览器下载，兼容性最好
				// #ifdef H5
				window.open(fileUrl, '_blank');
				uni.showToast({
					title: '下载已开始',
					icon: 'success'
				});
				// #endif

				// #ifdef APP-PLUS
				// App 环境使用 UniApp 下载
				uni.downloadFile({
					url: fileUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								showMenu: true // 显示菜单，允许用户保存
							});
						}
					}
				});
				// #endif
			},
			// 方案二
			// async simpleDownload(item) {
			// 	const fileUrl = `https://file.jinzhizixun.com.cn/${item}`;
			// 	const fileName = item;

			// 	uni.showLoading({
			// 		title: '下载中...',
			// 		mask: true
			// 	});

			// 	try {
			// 		// 判断环境
			// 		const isWeChatWork = navigator.userAgent.toLowerCase().includes('wxwork');

			// 		if (isWeChatWork) {
			// 			// 企业微信环境
			// 			await this.weChatDownload(fileUrl);
			// 		} else {
			// 			// 普通浏览器环境
			// 			this.browserDownload(fileUrl, fileName);
			// 		}

			// 		uni.showToast({
			// 			title: '下载成功',
			// 			icon: 'success'
			// 		});

			// 	} catch (error) {
			// 		console.error('下载失败:', error);
			// 		uni.showToast({
			// 			title: '下载失败',
			// 			icon: 'none'
			// 		});
			// 	} finally {
			// 		uni.hideLoading();
			// 	}
			// },

			// weChatDownload(fileUrl) {
			// 	return new Promise((resolve, reject) => {
			// 		if (typeof wx === 'undefined') {
			// 			reject(new Error('企业微信环境异常'));
			// 			return;
			// 		}
			// 		wx.downloadFile({
			// 			url: fileUrl,
			// 			success: (res) => {
			// 				if (res.statusCode === 200) {

			// 					wx.saveFile({
			// 						tempFilePath: res.tempFilePath,
			// 						success: resolve,
			// 						fail: reject
			// 					});
			// 				} else {
			// 					reject(new Error('下载失败'));
			// 				}
			// 			},
			// 			fail: reject
			// 		});
			// 	});
			// },

			// browserDownload(fileUrl, fileName) {
			// 	const link = document.createElement('a');
			// 	link.href = fileUrl;
			// 	link.download = fileName;
			// 	link.click();
			// },
			// 方案一
			async downloadFile() {
				try {
					// 下载文件到临时路径
					const downloadResult = await this.downloadToTemp();

					// 保存到本地
					const savedPath = await this.saveToLocal(downloadResult.tempFilePath);

					console.log('文件下载成功，保存路径:', savedPath);
					uni.showToast({
						title: '下载成功',
						icon: 'success'
					});

				} catch (error) {
					console.error('下载失败:', error);
					uni.showToast({
						title: '下载失败: ' + error.message,
						icon: 'none'
					});
				} finally {
					this.downloading = false;
				}
			},
			// 下载到临时路径
			downloadToTemp() {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url: this.ImageUrl,
						success: resolve,
						fail: reject
					});
				});
			},

			// 保存到本地
			saveToLocal(tempFilePath) {
				return new Promise((resolve, reject) => {
					// 平台特定的保存逻辑
					// #ifdef APP-PLUS
					this.saveInApp(tempFilePath, resolve, reject);
					// #endif

					// #ifdef H5
					this.saveInBrowser(tempFilePath, resolve, reject);
					// #endif

					// #ifdef MP-WEIXIN
					this.saveInWeChat(tempFilePath, resolve, reject);
					// #endif
				});
			},

			// 在App中保存
			saveInApp(tempFilePath, resolve, reject) {
				plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => {
					entry.copyTo(plus.io.PUBLIC_DOCUMENTS, this.fileName.url, (newEntry) => {
						resolve(newEntry.fullPath);
					}, reject);
				}, reject);


				// let dtask = plus.downloader.createDownload(url, {
				// 	filename: 'file://storage/emulated/0/金智咨询/' + this.fileName.url.split('/').pop()
				// }, (d, status) => {
				// 	//d为下载的文件对象
				// 	if (status == 200) {

				// 		uni.showToast({
				// 			icon: 'none',
				// 			mask: true,
				// 			title: '已保存到文件夹：/金智咨询/' + this.fileName.url.split('/').pop(), //保存路径
				// 			duration: 3000,
				// 		});

				// 		//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
				// 		let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
				// 		setTimeout(() => {
				// 			plus.runtime.openFile(d.filename); //选择软件打开文件
				// 		}, 1500)
				// 	} else {
				// 		//下载失败

				// 		plus.downloader.clear(); //清除下载任务
				// 		uni.showToast({
				// 			icon: 'none',
				// 			mask: true,
				// 			title: '下载失败，请稍后重试',
				// 		});
				// 	}
				// })
				// dtask.start();
			},
			// 在浏览器中保存
			saveInBrowser(tempFilePath, resolve, reject) {
				const link = document.createElement('a');
				link.href = tempFilePath;
				link.download = this.fileName.url.split('/').pop();
				link.style.display = 'none';

				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);

				resolve('浏览器下载文件夹/' + this.fileName.url.split('/').pop());
			},

			// 在微信小程序中保存
			saveInWeChat(tempFilePath, resolve, reject) {
				// wx.downloadFile({
				// 	url: tempFilePath,
				// 	success: (res) => {
				// 		// 保存到本地
				// 		wx.saveFile({
				// 			tempFilePath: res.tempFilePath,
				// 			success: (saveRes) => {
				// 				resolve(saveRes.savedFilePath);
				// 			},
				// 			fail: reject
				// 		});
				// 	},
				// 	fail: reject
				// });
				wx.downloadFile({
					url: this.ImageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							wx.saveFile({
								tempFilePath: res.tempFilePath,
								success: (saveRes) => {
									wx.showToast({
										title: '已保存到手机',
										icon: 'success'
									});
									resolve(saveRes.savedFilePath);
								},
								fail: (err) => {
									wx.showToast({
										title: '保存失败',
										icon: 'none'
									});
									reject(err);
								}
							});
						} else {
							reject(new Error(`下载失败，状态码: ${res.statusCode}`));
						}
					},
					fail: reject
				});
				// wx.saveFile({
				// 	tempFilePath: tempFilePath,
				// 	success: (res) => {
				// 		resolve(res.savedFilePath);
				// 	},
				// 	fail: reject
				// });
			}

		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
	}

	.card {
		background: #ffffff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.card-header {
		border-bottom: 1rpx solid #eeeeee;
		padding-bottom: 24rpx;
		margin-bottom: 24rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333333;
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.label {
		font-size: 28rpx;
		color: #666666;
		width: 180rpx;
		flex-shrink: 0;
	}

	.value {
		font-size: 28rpx;
		color: #333333;
		flex: 1;
		text-align: right;
	}

	.content-text {
		text-align: left;
		line-height: 1.6;
		color: #007AFF;
		margin: 5px 0;
		/* display: -webkit-box; */
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		/* line-height: 1.5; */
		/* 重要 */
	}

	.customer-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.customer-name {
		margin-left: 20rpx;
	}

	.name {
		display: block;
		font-size: 32rpx;
		font-weight: 600;
		color: #333333;
	}

	.company {
		display: block;
		font-size: 24rpx;
		color: #999999;
		margin-top: 8rpx;
	}

	.contact-info {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		background-color: #f5f7fa;
		padding: 10rpx;
		box-sizing: border-box;

	}

	.contact-btn {
		margin-left: 20rpx;
		color: #2979ff;
		font-size: 24rpx;
		padding: 8rpx 16rpx;
		border: 1rpx solid #2979ff;
		border-radius: 8rpx;
	}

	.status {
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
		font-size: 24rpx;
	}

	.overdue {
		background: #fff2f0;
		color: #ff4d4f;
		border: 1rpx solid #ffccc7;
	}

	.nodue {
		background: #ffffff;
		/* color: #ff4d4f; */
		/* border: 1rpx solid #ffccc7; */
	}

	.attachment-list {
		text-align: left;
	}

	.attachment-item {
		display: block;
		font-size: 26rpx;
		color: #2979ff;
		margin-bottom: 10rpx;
		padding: 8rpx 0;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 20rpx;
		border-top: 1rpx solid #eeeeee;
		display: flex;
		justify-content: center;
	}
</style>